package com.itheima.chapter11.tcp.case1;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket server =new ServerSocket(9999);
        System.out.println("服务端开启，等待客户端链接...");
        while(true){
            //响应客户发送的请求
            Socket socket =server.accept();
            //获取传输数据的流对象
            InputStream is = socket.getInputStream();
            OutputStream os = socket.getOutputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
            //读取上传文件名
            String fileName = br.readLine();
            //回写客户端消息（可以上传字节）
            bw.write("okk");
            bw.newLine();
            bw.flush();

            File file =new File("D:\\", UUID.randomUUID().toString()+fileName);

            //读取客户端上传文件（字节）
            FileOutputStream fos = new FileOutputStream(file);
            byte[] bys = new byte[1024];
            int len;
            while ((len = is.read(bys)) != -1) {
                fos.write(bys,0,len);
            }
            fos.close();

            bw.write("上传成功！");
            bw.newLine();
            bw.flush();

            socket.close();


        }

    }
}
